<?php
//早上 9 点执行
ini_set('display_errors', 1);
error_reporting(-1);
require_once '/data/wwwroot/g_vendor/autoload.php';

use Doraemon\model\Im\RabbitMessage;
use Doraemon\model\Im\RabbitMessageRelation;
use Biz\model\store\StoreBasic;
use Doraemon\service\Push\PushService;
use Doraemon\tools\Log;

//获取门店uid
const START_MSG_TIME = "22:00";
const END_MSG_TIME = "9:00";


$store_uids =  getAllStoreUids();
$uids = getSendPushUid($store_uids);
sendPush($uids);


function getAllStoreUids()
{
    $where=[];
    //$where['is_test'] = 1;
    $uids =  StoreBasic::getStoreByFilter($where ,'uid' );
    return $uids;
}


function getSendPushUid($storeUids)
{
    $uids = [];
    $info =  RabbitMessage::select(
        [
            "[>]" . RabbitMessageRelation::_TABLE_NAME => ["from_uid" => "from_uid" , 'to_uid' => "to_uid",'msgkey' => 'msgkey'],
        ],
        [
            RabbitMessage::_TABLE_NAME . ".id",
            RabbitMessage::_TABLE_NAME . ".to_uid",
            RabbitMessage::_TABLE_NAME . ".from_uid",
            RabbitMessage::_TABLE_NAME .'.add_time',
            RabbitMessageRelation::_TABLE_NAME . ".reply_time",
            RabbitMessageRelation::_TABLE_NAME . ".msgkey" ,

        ],
        [
            RabbitMessage::_TABLE_NAME . ".to_uid" => $storeUids,
            RabbitMessage::_TABLE_NAME . ".add_time[>=]" => strtotime(START_MSG_TIME),
            RabbitMessage::_TABLE_NAME . ".add_time[<]" => strtotime(END_MSG_TIME) + 86400,
            'GROUP' => [ RabbitMessage::_TABLE_NAME . ".to_uid" ,RabbitMessage::_TABLE_NAME . ".from_uid" ]
        ]
    );
    if($info && is_array($info)){
        foreach($info as $val){
            //未回复消息的用户
            if(empty($val['reply_time'])) {
                $uids[] = $val['to_uid'];
                continue;
            }
            //无回复
            if( $val['reply_time'] - $val['add_time'] < 0 ){
                $uids[] = $val['to_uid'];
            }
        }
    }
    return array_unique($uids);
}

function sendPush($uids){

if($uids && is_array($uids)){
    foreach ($uids as $uid){
        $pushId = 'push_store_im_' . date('Y_m_d');
        $params = [
            'uid' => $uid,
            'title' => '',
            'alert' => '有住友进行咨询啦，快点查看吧!',
            'param' => [
                'link' => "niceliving://message_center/designers",
                'push_id' => $pushId,
            ]
        ];
        PushService::send($params);
        //记录发送的push 日志
        //记录发送的消息日志
        Log::info(date("Y-m-d H:i:s").'-发送push 门店uid'.':'.$uid);
    }

}





}





